# coding=utf-8

import traceback
import os
import random
from selenium.common.exceptions import NoSuchElementException

# from unittest import TestCase

from src.newselenium.driver import Driver
from src.newselenium.by import By
from src.public.public import Public
from src.exception.seleniumexecption import SeleniumTypeError


class TestCaseMore(Public, object):
    def checkElement(self, by=By.ID, value=None):
        """
        说明：
            检查元素是否存在，如果存在则返回该元素对象，如果不存在则校验失败并在报告中体现
        :param by:
        :param value:
        :return: 存在则返回元素对象
        """
        if isinstance(self.driver, Driver):
            try:
                return self.driver.getelement(by=by, value=value)
                # self.driver.driver.find_element(by=by, value=value)
            except NoSuchElementException:
                self.assertTrue(
                    False, "未找到该元素，%s" % ("方式：" + str(by) + " 值：" + str(value))
                )
                return False
                # self.verificationErrors.append("未找到该元素，%s" % ("方式：" + str(by) + " 值：" + str(value)))
        else:
            raise SeleniumTypeError("self.driver 对象类型不对，应为Driver类，请检查...")

    # def reportPrint(self, msg: str) -> None:
    #     if isinstance(self, TestCase):
    #         self.assertTrue(False, msg)
    #     else:
    #         raise SeleniumTypeError("该对象无reportPrint()方法。")

    def get_screenshot(self):
        """
        说明：
            截图并会在测试报告中体现
            单独调试TestCase时，调用该方法不会在report目录下面生成截图文件
        """
        # print("module name:", self.__module__)
        # print("class name:", self.__class__.__name__)
        s = traceback.extract_stack()
        # print("function name:", s[-2][2])
        projectdir = os.path.dirname(
            os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        )  # 项目目录
        random_int = random.randint(10000000, 99999999)  # 随机数
        # 图片名称 需要拼上测试案例相关信息
        path = os.path.join(
            projectdir,
            "report",
            "tempimg",
            self.__module__
            + "."
            + self.__class__.__name__
            + "."
            + s[-2][2]
            + "_"
            + str(random_int)
            + ".png",
        )
        # 截图保存
        self.driver.get_screenshot(path=path)
